﻿using General.Core;
using General.Core.Model;
using General.Framework.Infrastructure;
using General.Framework.Security.Admin;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace General.Framework.Filters
{
    /// <summary>
    /// 登陆验证特性
    /// </summary>
    public class AdminAuthAttribute : TypeFilterAttribute
    {
        private readonly bool _ignoreFilter;

        public AdminAuthAttribute(bool ignore = false) : base(typeof(AdminAuthFilter))
        {
            _ignoreFilter = ignore;
            Arguments = new object[] { ignore };
        }

        public bool IgnoreFilter => _ignoreFilter;

        /// <summary>
        /// 
        /// </summary>
        private class AdminAuthFilter : IAuthorizationFilter
        {

            private readonly bool _ignoreFilter;
            private readonly IWorkContext _workContext;

            public AdminAuthFilter(bool ignore,
                IWorkContext workContext)
            {
                _workContext = workContext;
                _ignoreFilter = ignore;

            }

            public void OnAuthorization(AuthorizationFilterContext context)
            {
                var actionFilter = context.ActionDescriptor.FilterDescriptors.Where(filter => filter.Scope == FilterScope.Action)
                        .Select(filter => filter.Filter).OfType<AdminAuthAttribute>().FirstOrDefault();

                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                    return;

                if (context.Filters.Any(filter => filter is AdminAuthFilter))
                {
                    var user = _workContext.CurrentUser;
                    if (user == null)
                    {
                        if (context.HttpContext.Request.IsAjaxRequest())
                        {
                            ApiJsonResult apiJsonResult = new ApiJsonResult() { code = 1003, msg = "未登录或已过期" };
                            context.Result = new JsonResult(apiJsonResult);
                        }
                        else
                        {
                            if (user == null || !user.Enabled)
                                context.Result = new RedirectToRouteResult("adminLogin", new { returnUrl = context.HttpContext.Request.Path });
                        }
                    }
                }
            }
             

        }


    } 
   
}
